package com.example.foods.controller;

import cn.hutool.core.util.StrUtil;
import com.example.foods.common.Constants;
import com.example.foods.domain.AdminInfo;
import com.example.foods.domain.AjaxResult;
import com.example.foods.domain.CustomersInfo;
import com.example.foods.domain.UpdatePwdInfo;
import com.example.foods.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private CustomerService customerService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody CustomersInfo customersInfo, BindingResult bindingResult, HttpSession httpSession) {
        //有校验错误
        if (bindingResult.hasFieldErrors()) {
            return AjaxResult.error(-1, "请求无效!");
        }
        CustomersInfo customersInfo1 = this.customerService.findBycst(customersInfo.getCst_mobile());
        if (customersInfo1 == null ) {
            return AjaxResult.error(-1, "账号或密码不正确!");
        } else {
            //登录成功后，会将用户对象存入session中，以便后续进行权限检查
            httpSession.setAttribute(Constants.SESSION_KEY_LOGINED_USER, customersInfo1);
            httpSession.setAttribute("userId", customersInfo1.getCst_Id());
            return AjaxResult.ok(customersInfo1);
        }
    }

    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestBody UpdatePwdInfo updatePwdInfo) {
        if(StrUtil.isBlank(updatePwdInfo.getPwd())){
            log.error("密码未输入");
            AjaxResult.ok(false);
        }
        customerService.updatePwd(updatePwdInfo);

        return AjaxResult.ok(true);
    }

    @GetMapping("/list")
    public AjaxResult list() {
        return AjaxResult.ok(this.customerService.list());
    }

    //删除
    @GetMapping("/delete/{cstId}")
    public void delete(@PathVariable Integer cstId, HttpServletResponse response)
            throws IOException {
        this.customerService.delete(cstId);
        //重定向
        String redirectUrl = "http://localhost:8080/user/user_list.html";
        response.sendRedirect(redirectUrl);
    }

}
